package com.lzh.redis.conf;

import com.lzh.redis.entity.User;
import com.lzh.redis.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义UserRealm
public class UserRealm  extends AuthorizingRealm{
    @Autowired
    private UserService userService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了用户授权+=================================>");
        SimpleAuthorizationInfo Info = new SimpleAuthorizationInfo();
        //获取当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        //拿到currentUser对象
        User currentUser = (User) subject.getPrincipal();
        //获取用户的权限   =》("") 这里获取当前对象的权限
        Info.addStringPermission(currentUser.getPerms());
        return Info;
    }

    /**
     * 认证
     * @param Token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
        //执行认证功能
        System.out.println("执行了用户认证+=================================>");
        UsernamePasswordToken token = (UsernamePasswordToken) Token;
        String username = token.getUsername();
        User queryUser = new User();
        queryUser.setUsername(username);
        User user = userService.queryUserByUsername(queryUser);
        if (user == null){
            return null;
        }
        // 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        //获取session
        Session session = currentUser.getSession();
        //将用户存入session中
        session.setAttribute("loginUser",user);

        /*可以加密，  md5 加密  MD5 盐值加密*/
        return new SimpleAuthenticationInfo(user,user.getPassword(),getName());
    }
}
